package com.spring.service.file;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.spring.domain.File;
import com.spring.service.util.FileMapper;
import com.spring.service.util.UserMapper;

public class JdbcFileDao extends SimpleJdbcDaoSupport implements FileDao {
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	public List<File> getFiles() {
		return getSimpleJdbcTemplate().query( "select id, name, description, type from file", new FileMapper());
	}

	public int insertFile(File file) {
		logger.info("Saving file: " + file.getName());
		int count = getSimpleJdbcTemplate()
				.update("insert file (name, description, type) values (:name, :description, :type)",
						FileMapper.sqlMap(file));
		logger.info("Rows affected: " + count);
		
		return getJdbcTemplate().queryForInt( "select last_insert_id()" );
	}

	public void deleteFile(List<File> files) {
		logger.info("deleting files: " + files.toString());
		String idList="";
		for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
			File file = (File) iterator.next();
			idList+=file.getId();
			if (iterator.hasNext())idList+=",";
		}
		getJdbcTemplate().execute("delete from file where id in ("+idList+")");
		getJdbcTemplate().execute("delete from rel_cont_file where id_file in ("+idList+")");
		getJdbcTemplate().execute("delete from rel_cont_img where id_file in ("+idList+")");
		
		logger.info("files deleted");
	}

	public int updateFile(File file) {
		int count = getSimpleJdbcTemplate()
				.update("update file set description=:description where id=:id",
						FileMapper.sqlMap(file));
		return count;
	}

	public List<File> selectByType(String type) {
		return null;
	}

	public File selectById(int id) {
		return (getSimpleJdbcTemplate().query( "select  id, name, description, type from file where id="+id, new FileMapper())).get(0);
	}

}
